package com.fj.concurrent;

import java.util.Random;
import java.util.concurrent.CountDownLatch;

/**
 * @author fj
 * @date 2023/11/29 17:21
 */
public class CountDownLaunchTest {

    public static void main(String[] args) throws Exception{
        System.out.println("hello world");
        //无顺序
//        new Thread(new CustomTask2()).start();
//        new Thread(new CustomTask2()).start();
//        new Thread(new CustomTask2()).start();
        //主线程最后
//        CountDownLatch countDownLatch = new CountDownLatch(3);
//        new Thread(new CustomTask(countDownLatch)).start();
//        new Thread(new CustomTask(countDownLatch)).start();
//        new Thread(new CustomTask(countDownLatch)).start();
//        countDownLatch.await();
        //保证子线程处于同一时间竞争
        CountDownLatch countDownLatch = new CountDownLatch(1);
        new Thread(new CustomTask3(countDownLatch)).start();
        new Thread(new CustomTask3(countDownLatch)).start();
        new Thread(new CustomTask3(countDownLatch)).start();
        countDownLatch.countDown();
        System.out.println(Thread.currentThread().getName()+" finished");
    }

    static class CustomTask implements Runnable{

        private CountDownLatch countDownLatch;

        CustomTask(CountDownLatch countDownLatch){
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {
//            Random random = new Random();
//            long l = random.nextLong(1000, 5000);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName()+" finished");
            countDownLatch.countDown();
        }
    }

    static class CustomTask2 implements Runnable{

        @Override
        public void run() {
//            Random random = new Random();
//            long l = random.nextLong(1000, 5000);
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName()+" finished");
        }
    }

    static class CustomTask3 implements Runnable{

        private CountDownLatch countDownLatch;

        CustomTask3(CountDownLatch countDownLatch){
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {
            try {
                countDownLatch.await();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println(Thread.currentThread().getName()+" finished");
        }
    }
}
